from django import forms
from django.core.exceptions import ValidationError

from web import models
from web.forms.bootstrap import BootStrapForm


class FileModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.FileRepository
        fields = ['name']

    def __init__(self, request, parent_obj, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_obj = parent_obj

    def clean_name(self):
        name = self.cleaned_data['name']

        if self.parent_obj:
            exists = models.FileRepository.objects.filter(parent=self.parent_obj, name=name,
                                                          project=self.request.tracer.project, file_type=1).exists()
        else:
            exists = models.FileRepository.objects.filter(parent__isnull=True, name=name,
                                                          project=self.request.tracer.project,
                                                          file_type=1).exists()
        if exists:
            raise ValidationError("文件夹已存在")

        return name


class CheckFileModelForm(forms.ModelForm):
    file_etag = forms.CharField(label='Etag')

    class Meta:
        model = models.FileRepository
        exclude = ['project', 'file_type', 'update_user', 'update_datetime']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_file_path(self):
        file_path = self.cleaned_data['file_path']
        file_path = f"https://{file_path}"
        return file_path

